import { Component, Prop } from "vue-property-decorator";
import { Form } from "ant-design-vue";
import { IFormProps } from "@/types/form";
import { VC } from "@/VC-vue";
import { FormUtils } from "@/types/form-ref";

const props = [
    "layout",
    "itemList",
    "labelCol",
    "col",
    "form",
    "wrapperCol",
    "itemStyle",
    "initialValues",
    "hidden"
];

@Component({ props })
class Iform extends VC<IFormProps> {
    @Prop() form!: FormUtils;

    get renderItem() {
        const {
            labelCol,
            wrapperCol,
            initialValues,
            itemStyle,
            col,
            itemList
        } = this.$props;
        const form = this.form;

        return (itemList || []).map(props => {
            // tslint:disable-next-line:prefer-const
            let { field, rules, initialValue, el, hidden } = props;
            let element: any = (
                <a-input type={props.type} placeholder={props.placeholder} />
            );
            el && (element = typeof el === "function" ? el(form) : el);
            typeof rules === "function" && (rules = rules(form));
            if (field) {
                initialValues &&
                    Object.keys(initialValues).includes(field) &&
                    (initialValue = initialValues[field]);
                element = form.getFieldDecorator(field, {
                    rules,
                    initialValue
                })(element);
            }

            const formItemProps = { props: { labelCol, wrapperCol, ...props } };
            const colProps = { props: col };
            const style = props.style || itemStyle;
            return hidden ? (
                ""
            ) : colProps.props ? (
                <a-col {...colProps} style={style}>
                    <a-form-item {...formItemProps}>{element}</a-form-item>
                </a-col>
            ) : (this.$props.itemList as any).length > 12 ? (
                <a-col span={12}>
                    <a-form-item style="margin-bottom:20px" {...formItemProps}>
                        {element}
                    </a-form-item>
                </a-col>
            ) : (
                <a-form-item style="margin-bottom:20px" {...formItemProps}>
                    {element}
                </a-form-item>
            );
        });
    }

    render() {
        return (
            <a-row>
                <a-form layout={this.$props.layout}>
                    <a-row>{this.renderItem}</a-row>
                </a-form>
            </a-row>
        );
    }
}

const MForm = Form.create({ props })(Iform);
const IForm = ({ data }: FC<IFormProps>) => <MForm {...data} />;

export default IForm;
